package com.example.tool.actions;

import com.example.tool.entity.ConfigEntity;
import com.example.tool.module.ModuleInformation;
import com.example.tool.module.ModuleInputEnum;
import com.example.tool.ui.HToolIcon;
import com.example.tool.ui.HToolViewItem;
import com.example.tool.ui.SwingUi;
import com.example.tool.ui.SwingViewWrapper;
import com.example.tool.utils.ActionToolUtil;
import com.example.tool.utils.FileUtil;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.TextBrowseFolderListener;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiManager;
import com.intellij.ui.components.JBTextField;
import org.jetbrains.annotations.NotNull;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class ConfigAction extends AnAction {
  private static final Logger LOG = Logger.getInstance(ConfigAction.class);

  public ConfigAction() {
    super(ModuleInformation.CONFIG_ACTION, null, HToolIcon.CONFIG);
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    try {
      if (project != null) {
        TextFieldWithBrowseButton rootPath = new TextFieldWithBrowseButton();
        FileChooserDescriptor fileChooserDescriptor = new FileChooserDescriptor(false, true, false, false, false, false);
        rootPath.addBrowseFolderListener(new TextBrowseFolderListener(fileChooserDescriptor));
        JBTextField plugId = new JBTextField();
        JBTextField buildPath = new JBTextField();
        Module[] modules = ModuleManager.getInstance(project).getModules();
        List<String> sourceAll = new ArrayList<>();
        Arrays.stream(modules).forEach(module -> {
          ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
          VirtualFile[] sourceRoots = moduleRootManager.getSourceRoots();
          for (VirtualFile sourceRoot : sourceRoots) {
            String name = sourceRoot.getName();
            sourceAll.add(name);
          }
        });
        String[] toBeStored = sourceAll.toArray(new String[0]);
        ComboBox<String> comboBoxHas = new ComboBox<>(toBeStored);
        ConfigEntity configEntity = ActionToolUtil.getInformation(project);
        if (configEntity != null) {
          rootPath.setText(configEntity.getProjectPath());
          String pluginID = configEntity.getPluginID();
          plugId.setText(pluginID);
          buildPath.setText(configEntity.getBuildPath());
          String sourcePath = configEntity.getSourcePath();
          if (sourcePath == null || sourcePath.isEmpty()) {
            if (pluginID != null && !pluginID.isEmpty()) {
              comboBoxHas.setSelectedItem("src_" + pluginID);
            } else {
              comboBoxHas.setSelectedItem("");
            }
          } else {
            comboBoxHas.setSelectedItem(sourcePath);
          }
        } else {
          buildPath.setText(ModuleInformation.DIRECTORY);
        }
        List<HToolViewItem<?>> hToolViewItems = new ArrayList<>();
        hToolViewItems.add(new HToolViewItem<>(ModuleInputEnum.ROOT_PATH, rootPath));
        hToolViewItems.add(new HToolViewItem<>(ModuleInputEnum.ROUSE_PATH, comboBoxHas));
        hToolViewItems.add(new HToolViewItem<>(ModuleInputEnum.PLUG_ID, plugId, true));
        hToolViewItems.add(new HToolViewItem<>(ModuleInputEnum.BUILD_PATH, buildPath));
        SwingViewWrapper configDialogWrapper = new SwingViewWrapper(project, ModuleInformation.CONFIG_INFO, ModuleInformation.TIP_CONFIG, hToolViewItems, true);
        configDialogWrapper.inspect((key, value) -> {
          if (key.equals(ModuleInputEnum.PLUG_ID) && !SwingUi.IsEnglish(value)) {
            throw new Exception(ModuleInformation.PLUG_ID_MSG);
          }
        });
        // 按下ok按键
        if (configDialogWrapper.showAndGet()) {
          Map<ModuleInputEnum, String> values = configDialogWrapper.getValues();
          exec(project, values);
        }
      }
    } catch (Exception ex) {
      String text = getTemplatePresentation().getText();
      String textParse = ModuleInformation.textParse(ModuleInformation.OPEN_ACTION_MSG, text);
      LOG.info(textParse + ex.getMessage());
      ActionToolUtil.showNotification(project, NotificationType.ERROR, textParse);
    }
  }

  private void exec(Project project, Map<ModuleInputEnum, String> values) {
    Application application = ApplicationManager.getApplication();
    application.runWriteAction(() -> {
      try {
        PsiManager psiManager = PsiManager.getInstance(project);
        LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
        String basePath = project.getBasePath();
        if (basePath != null) {
          String root_path = values.get(ModuleInputEnum.ROOT_PATH);
          String rouse_path = values.get(ModuleInputEnum.ROUSE_PATH);
          String plug_id = values.get(ModuleInputEnum.PLUG_ID);
          String build_path = values.get(ModuleInputEnum.BUILD_PATH);
          ConfigEntity configEntity = ActionToolUtil.getInformation(project);
          String sshID;
          boolean xmlNeedChange = false;
          if (configEntity != null) {
            String projectPath = configEntity.getProjectPath();
            String pluginID = configEntity.getPluginID();
            String buildPath = configEntity.getBuildPath();
            String sourcePath = configEntity.getSourcePath();
            sshID = configEntity.getSshID();
            xmlNeedChange = projectPath.equals(root_path) && buildPath.equals(build_path);
            // 如果配置文件没有变化，则不执行
            if (xmlNeedChange && pluginID.equals(plug_id) && rouse_path.equals(sourcePath)) {
              return;
            }
            if (!xmlNeedChange && (sshID == null || sshID.equals("null") || sshID.isEmpty())) {
              sshID = UUID.randomUUID().toString();
            }
            configEntity.setProjectPath(root_path);
            configEntity.setPluginID(plug_id);
            configEntity.setBuildPath(build_path);
            configEntity.setSshID(sshID);
            configEntity.setSourcePath(rouse_path);
          } else {
            sshID = UUID.randomUUID().toString();
            configEntity = new ConfigEntity(root_path, plug_id, build_path, sshID, rouse_path);
          }
          Path path = Path.of(basePath, ".idea");
          VirtualFile fileByNioFile = localFileSystem.findFileByNioFile(path);
          if (fileByNioFile != null) {
            fileByNioFile.refresh(false, true);
            PsiDirectory psiBaseDir = psiManager.findDirectory(fileByNioFile);
            if (psiBaseDir == null) {
              ActionToolUtil.showSetting(project);
              return;
            }
            if (!xmlNeedChange) {
              boolean pluginInstalled = PluginManagerCore.isPluginInstalled(PluginId.getId("com.jetbrains.plugins.webDeployment"));
              configEntity.setSshID(null);
              ActionToolUtil.showSync(project, pluginInstalled);
            }
            FileUtil.createOther(project, psiBaseDir, ModuleInformation.MODULE_CONFIG, configEntity.finalResult());
          }
        }
      } catch (Exception ex) {
        LOG.info(ex.getMessage(), ex);
      }
    });
  }


}
